<template>
  <div class="operation-logs">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>操作日志</h1>
      <p>查看系统操作记录和用户行为日志</p>
    </div>

    <!-- 筛选器 -->
    <div class="filters-section">
      <div class="filters-row">
        <div class="filter-item">
          <label>操作类型</label>
          <select v-model="filters.operation">
            <option value="">全部操作</option>
            <option value="login">用户登录</option>
            <option value="logout">用户登出</option>
            <option value="create">创建操作</option>
            <option value="update">更新操作</option>
            <option value="delete">删除操作</option>
            <option value="exam">考试操作</option>
            <option value="system">系统操作</option>
          </select>
        </div>
        
        <div class="filter-item">
          <label>用户角色</label>
          <select v-model="filters.role">
            <option value="">全部角色</option>
            <option value="super-admin">超级管理员</option>
            <option value="teacher">教师</option>
            <option value="student">学生</option>
          </select>
        </div>
        
        <div class="filter-item">
          <label>日期范围</label>
          <input v-model="filters.startDate" type="date" />
          <span>至</span>
          <input v-model="filters.endDate" type="date" />
        </div>
        
        <div class="filter-item">
          <label>用户搜索</label>
          <input v-model="filters.username" type="text" placeholder="输入用户名" />
        </div>
        
        <div class="filter-actions">
          <button @click="applyFilters" class="btn btn-primary">筛选</button>
          <button @click="resetFilters" class="btn btn-secondary">重置</button>
          <button @click="exportLogs" class="btn btn-outline">导出</button>
        </div>
      </div>
    </div>

    <!-- 日志列表 -->
    <div class="logs-section">
      <div class="logs-header">
        <h3>操作记录 ({{ filteredLogs.length }})</h3>
        <div class="refresh-btn">
          <button @click="refreshLogs" class="btn btn-icon">
            <i class="fas fa-sync-alt"></i>
            刷新
          </button>
        </div>
      </div>
      
      <div class="logs-table">
        <div class="table-header">
          <div class="col-time">时间</div>
          <div class="col-user">用户</div>
          <div class="col-role">角色</div>
          <div class="col-operation">操作类型</div>
          <div class="col-description">操作描述</div>
          <div class="col-ip">IP地址</div>
          <div class="col-status">状态</div>
        </div>
        
        <div class="table-body">
          <div 
            v-for="log in paginatedLogs" 
            :key="log.id" 
            class="table-row"
            :class="{ 'error': log.status === 'error', 'warning': log.status === 'warning' }"
          >
            <div class="col-time">
              <span class="timestamp">{{ formatTime(log.timestamp) }}</span>
            </div>
            <div class="col-user">
              <div class="user-info">
                <span class="username">{{ log.username }}</span>
                <span class="user-id">{{ log.userId }}</span>
              </div>
            </div>
            <div class="col-role">
              <span class="role-tag" :class="log.role">{{ getRoleLabel(log.role) }}</span>
            </div>
            <div class="col-operation">
              <span class="operation-tag" :class="log.operation">{{ getOperationLabel(log.operation) }}</span>
            </div>
            <div class="col-description">
              <span class="description">{{ log.description }}</span>
              <div v-if="log.details" class="details">
                <button @click="toggleDetails(log.id)" class="btn-link">
                  {{ expandedLogs.includes(log.id) ? '收起' : '详情' }}
                </button>
              </div>
              <div v-if="expandedLogs.includes(log.id) && log.details" class="log-details">
                <pre>{{ JSON.stringify(log.details, null, 2) }}</pre>
              </div>
            </div>
            <div class="col-ip">
              <span class="ip-address">{{ log.ipAddress }}</span>
              <span class="location">{{ log.location }}</span>
            </div>
            <div class="col-status">
              <span class="status-indicator" :class="log.status">{{ getStatusLabel(log.status) }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <button 
          @click="currentPage--" 
          :disabled="currentPage <= 1"
          class="btn btn-secondary"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        <button 
          @click="currentPage++" 
          :disabled="currentPage >= totalPages"
          class="btn btn-secondary"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'

export default {
  name: 'OperationLogs',
  setup() {
    const filters = ref({
      operation: '',
      role: '',
      startDate: '',
      endDate: '',
      username: ''
    })
    
    const currentPage = ref(1)
    const pageSize = ref(20)
    const expandedLogs = ref([])
    
    // 模拟日志数据
    const logs = ref([
      {
        id: 1,
        timestamp: '2024-01-15T10:30:25',
        username: 'admin',
        userId: 'admin001',
        role: 'super-admin',
        operation: 'login',
        description: '管理员登录系统',
        ipAddress: '192.168.1.100',
        location: '北京市',
        status: 'success',
        details: {
          userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
          sessionId: 'sess_123456'
        }
      },
      {
        id: 2,
        timestamp: '2024-01-15T10:25:12',
        username: '张老师',
        userId: 'teacher001',
        role: 'teacher',
        operation: 'create',
        description: '创建新考试：《数据结构期末考试》',
        ipAddress: '192.168.1.101',
        location: '上海市',
        status: 'success',
        details: {
          examId: 'exam_001',
          examTitle: '数据结构期末考试',
          duration: 120
        }
      },
      {
        id: 3,
        timestamp: '2024-01-15T10:20:08',
        username: '学生001',
        userId: 'student001',
        role: 'student',
        operation: 'exam',
        description: '提交考试答案',
        ipAddress: '192.168.1.102',
        location: '广州市',
        status: 'success',
        details: {
          examId: 'exam_001',
          score: 85,
          duration: 115
        }
      },
      {
        id: 4,
        timestamp: '2024-01-15T10:15:30',
        username: 'system',
        userId: 'system',
        role: 'system',
        operation: 'system',
        description: '系统自动备份数据库',
        ipAddress: '127.0.0.1',
        location: '本地',
        status: 'success',
        details: {
          backupSize: '125.6MB',
          backupPath: '/backup/db_20240115.sql'
        }
      },
      {
        id: 5,
        timestamp: '2024-01-15T10:10:15',
        username: '李老师',
        userId: 'teacher002',
        role: 'teacher',
        operation: 'delete',
        description: '删除过期考试',
        ipAddress: '192.168.1.103',
        location: '深圳市',
        status: 'warning',
        details: {
          examId: 'exam_old_001',
          examTitle: '过期测试考试'
        }
      },
      {
        id: 6,
        timestamp: '2024-01-15T10:05:45',
        username: '学生002',
        userId: 'student002',
        role: 'student',
        operation: 'login',
        description: '学生登录失败 - 密码错误',
        ipAddress: '192.168.1.104',
        location: '杭州市',
        status: 'error',
        details: {
          reason: 'Invalid password',
          attempts: 3
        }
      }
    ])
    
    const filteredLogs = computed(() => {
      return logs.value.filter(log => {
        if (filters.value.operation && log.operation !== filters.value.operation) return false
        if (filters.value.role && log.role !== filters.value.role) return false
        if (filters.value.username && !log.username.includes(filters.value.username)) return false
        if (filters.value.startDate && log.timestamp < filters.value.startDate) return false
        if (filters.value.endDate && log.timestamp > filters.value.endDate + 'T23:59:59') return false
        return true
      })
    })
    
    const totalPages = computed(() => {
      return Math.ceil(filteredLogs.value.length / pageSize.value)
    })
    
    const paginatedLogs = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredLogs.value.slice(start, end)
    })
    
    const formatTime = (timestamp) => {
      return new Date(timestamp).toLocaleString('zh-CN')
    }
    
    const getRoleLabel = (role) => {
      const labels = {
        'super-admin': '超级管理员',
        'teacher': '教师',
        'student': '学生',
        'system': '系统'
      }
      return labels[role] || role
    }
    
    const getOperationLabel = (operation) => {
      const labels = {
        'login': '登录',
        'logout': '登出',
        'create': '创建',
        'update': '更新',
        'delete': '删除',
        'exam': '考试',
        'system': '系统'
      }
      return labels[operation] || operation
    }
    
    const getStatusLabel = (status) => {
      const labels = {
        'success': '成功',
        'warning': '警告',
        'error': '错误'
      }
      return labels[status] || status
    }
    
    const toggleDetails = (logId) => {
      const index = expandedLogs.value.indexOf(logId)
      if (index > -1) {
        expandedLogs.value.splice(index, 1)
      } else {
        expandedLogs.value.push(logId)
      }
    }
    
    const applyFilters = () => {
      currentPage.value = 1
      // 这里可以调用API重新获取数据
    }
    
    const resetFilters = () => {
      filters.value = {
        operation: '',
        role: '',
        startDate: '',
        endDate: '',
        username: ''
      }
      currentPage.value = 1
    }
    
    const refreshLogs = () => {
      // 这里可以调用API刷新数据
      console.log('刷新日志数据')
    }
    
    const exportLogs = () => {
      // 这里可以实现导出功能
      alert('导出功能开发中...')
    }
    
    onMounted(() => {
      // 初始化数据
    })
    
    return {
      filters,
      currentPage,
      pageSize,
      expandedLogs,
      logs,
      filteredLogs,
      totalPages,
      paginatedLogs,
      formatTime,
      getRoleLabel,
      getOperationLabel,
      getStatusLabel,
      toggleDetails,
      applyFilters,
      resetFilters,
      refreshLogs,
      exportLogs
    }
  }
}
</script>

<style scoped>
.operation-logs {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.filters-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filters-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: end;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-item label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.filter-item select,
.filter-item input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 120px;
}

.filter-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.logs-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.logs-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.logs-table {
  border: 1px solid #e5e6eb;
  border-radius: 6px;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 140px 120px 80px 100px 1fr 120px 80px;
  background: #f8f9fa;
  font-weight: 600;
  font-size: 14px;
  color: #333;
}

.table-header > div {
  padding: 12px 16px;
  border-right: 1px solid #e5e6eb;
}

.table-header > div:last-child {
  border-right: none;
}

.table-body {
  max-height: 600px;
  overflow-y: auto;
}

.table-row {
  display: grid;
  grid-template-columns: 140px 120px 80px 100px 1fr 120px 80px;
  border-bottom: 1px solid #e5e6eb;
  font-size: 14px;
}

.table-row:hover {
  background: #f8f9fa;
}

.table-row.error {
  background: #fff2f0;
}

.table-row.warning {
  background: #fffbe6;
}

.table-row > div {
  padding: 12px 16px;
  border-right: 1px solid #e5e6eb;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.table-row > div:last-child {
  border-right: none;
}

.timestamp {
  color: #666;
  font-size: 12px;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.username {
  font-weight: 500;
}

.user-id {
  font-size: 12px;
  color: #999;
}

.role-tag {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
}

.role-tag.super-admin {
  background: #ff4d4f;
  color: white;
}

.role-tag.teacher {
  background: #1890ff;
  color: white;
}

.role-tag.student {
  background: #52c41a;
  color: white;
}

.role-tag.system {
  background: #722ed1;
  color: white;
}

.operation-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
}

.operation-tag.login {
  background: #e6f7ff;
  color: #1890ff;
}

.operation-tag.logout {
  background: #f6ffed;
  color: #52c41a;
}

.operation-tag.create {
  background: #f0f5ff;
  color: #2f54eb;
}

.operation-tag.update {
  background: #fff7e6;
  color: #fa8c16;
}

.operation-tag.delete {
  background: #fff2f0;
  color: #ff4d4f;
}

.operation-tag.exam {
  background: #f9f0ff;
  color: #722ed1;
}

.operation-tag.system {
  background: #f0f0f0;
  color: #666;
}

.description {
  font-weight: 500;
}

.details {
  margin-top: 4px;
}

.btn-link {
  background: none;
  border: none;
  color: #1890ff;
  cursor: pointer;
  font-size: 12px;
  text-decoration: underline;
}

.log-details {
  margin-top: 8px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  font-size: 12px;
}

.log-details pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}

.ip-address {
  font-family: monospace;
  font-size: 12px;
}

.location {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.status-indicator {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
}

.status-indicator.success {
  background: #f6ffed;
  color: #52c41a;
}

.status-indicator.warning {
  background: #fffbe6;
  color: #faad14;
}

.status-indicator.error {
  background: #fff2f0;
  color: #ff4d4f;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 24px;
}

.page-info {
  color: #666;
  font-size: 14px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background: #1890ff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #40a9ff;
}

.btn-secondary {
  background: #f0f0f0;
  color: #666;
}

.btn-secondary:hover:not(:disabled) {
  background: #d9d9d9;
}

.btn-outline {
  background: white;
  color: #1890ff;
  border: 1px solid #1890ff;
}

.btn-outline:hover {
  background: #f0f5ff;
}

.btn-icon {
  background: #f0f0f0;
  color: #666;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-icon:hover {
  background: #d9d9d9;
}

@media (max-width: 1200px) {
  .table-header,
  .table-row {
    grid-template-columns: 120px 100px 70px 80px 1fr 100px 70px;
  }
}

@media (max-width: 768px) {
  .filters-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-actions {
    margin-left: 0;
    justify-content: flex-start;
  }
  
  .table-header,
  .table-row {
    grid-template-columns: 1fr;
    grid-template-rows: repeat(7, auto);
  }
  
  .table-header > div,
  .table-row > div {
    border-right: none;
    border-bottom: 1px solid #e5e6eb;
    padding: 8px 16px;
  }
  
  .table-header > div:last-child,
  .table-row > div:last-child {
    border-bottom: none;
  }
}
</style>